package com.xujianlun.cpms.service.sys.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xujianlun.cpms.common.ResponseCode;
import com.xujianlun.cpms.common.ValidationEnum;
import com.xujianlun.cpms.entity.sys.Validation;
import com.xujianlun.cpms.exception.ServiceException;
import com.xujianlun.cpms.service.sys.EmailService;
import com.xujianlun.cpms.service.sys.IValidationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

/**
 * @version 1.0
 * @Author xujianlun
 * @Date 2022/12/4 15:14
 * @注释 邮箱业务实现类
 */
@Service
public class EmailServiceImpl implements EmailService {
    // 用于发送邮件的对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Resource
    private IValidationService validationService;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 密码找回操作
     * @param email 邮箱地址
     * @param name 用户名
     */
    @Override
    public void sendEmailCode(String email, String name) {
        Date now = new Date();
        //先查询同类型的code
        QueryWrapper<Validation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",email);
        queryWrapper.ge("time",now);//查询数据库没过期的code
        queryWrapper.eq("type",ValidationEnum.FORGET_PASSWORD.getCode());
        Validation validation = validationService.getOne(queryWrapper);
        if (validation !=null){
            throw new ServiceException(-1,"当前您的验证码5分钟内仍然有效，请不要重复发送");
        }
        // 设置验证码，随机生成
        Random random = new Random();
        String code = String.valueOf(random.nextInt(9000)+1000);

        try {
            // 用来设置邮件信息
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            // 设置邮件标题
            simpleMailMessage.setSubject("疫情防控管理系统");
            //当前时间
            simpleMailMessage.setSentDate(now);
            // 设置邮件内容
            simpleMailMessage.setText("亲爱的"+name+":\n      您正在进行密码找回，验证码是：" + code+",请在5分钟之内完成验证。\n      如果不是本人的操作，打死也不要告诉任何人哦!");
            // 设置源邮箱
            simpleMailMessage.setFrom(from);
            // 设置目的邮箱
            simpleMailMessage.setTo(email);
            // 发送
            javaMailSender.send(simpleMailMessage);
            //发送成功之后把验证码存到数据库
            validationService.saveCode(email,code, ValidationEnum.FORGET_PASSWORD.getCode(), DateUtil.offsetMinute(now,5));
        } catch (MailException e) {
            throw new ServiceException(ResponseCode.ERROR_CODE500);
        }
        // 没有出现异常，正常发送，返回验证码到前台等待验证
    }
}
